<template>
    <view class="container order-container">
        <!-- 状态切换标签 -->
        <scroll-view scroll-x="true" class="order-tab-scroll" :scroll-into-view="'tab-' + activeTab"
            scroll-with-animation>
            <view class="order-tab-bar">
                <view class="order-tab-item" id="tab-all" :class="{ active: activeTab === 'all' }"
                    @click="switchTab('all')">
                    <text>全部</text>
                    <view class="tab-line" v-if="activeTab === 'all'"></view>
                </view>
                <view class="order-tab-item" id="tab-pending" :class="{ active: activeTab === 'pending' }"
                    @click="switchTab('pending')">
                    <text>待付款</text>
                    <view class="tab-line" v-if="activeTab === 'pending'"></view>
                </view>
                <view class="order-tab-item" id="tab-unused" :class="{ active: activeTab === 'unused' }"
                    @click="switchTab('unused')">
                    <text>未使用</text>
                    <view class="tab-line" v-if="activeTab === 'unused'"></view>
                </view>
                <view class="order-tab-item" id="tab-using" :class="{ active: activeTab === 'using' }"
                    @click="switchTab('using')">
                    <text>使用中</text>
                    <view class="tab-line" v-if="activeTab === 'using'"></view>
                </view>
                <view class="order-tab-item" id="tab-finished" :class="{ active: activeTab === 'finished' }"
                    @click="switchTab('finished')">
                    <text>已完成</text>
                    <view class="tab-line" v-if="activeTab === 'finished'"></view>
                </view>
                <view class="order-tab-item" id="tab-canceled" :class="{ active: activeTab === 'canceled' }"
                    @click="switchTab('canceled')">
                    <text>已取消</text>
                    <view class="tab-line" v-if="activeTab === 'canceled'"></view>
                </view>
            </view>
        </scroll-view>

        <!-- 内容区域 -->
        <view class="content">
            <!-- 有订单时显示 -->
            <view v-if="orderList.length > 0" class="order-list">
                <!-- 动态渲染订单列表 -->
                <view class="order-item" v-for="(order, index) in orderList" :key="order.id" @click="goToOrderDetail(order.id)">
                    <view class="order-header">
                        <view class="store-info">
                            <view class="store-icon">
                                <image src="/static/icon/商店.png" class="icon-small"></image>
                            </view>
                            <text class="store-name">幸运棋牌</text>
                        </view>
                        <text class="order-status" :class="getStatusClass(order.status)">{{getStatusText(order.status)}}</text>
                    </view>
                    <view class="order-content">
                        <view class="room-info">
                            <image class="room-image"
                                :src="order.room_image || 'https://ai-public.mastergo.com/ai/img_res/dbef5d324519a8ea1d7dd7b355c94871.jpg'"
                                mode="aspectFill"></image>
                            <view class="room-details">
                                <view class="room-name">{{order.room_name || '房间名称'}}</view>
                                <view class="room-time">时长：{{order.duration || 0}}小时</view>
                                <view class="room-reservation time-no-wrap">
                                    预订时段：{{formatDate(order.date)}} {{order.start_time}} 至 
                                    {{order.is_next_day ? formatNextDay(order.date) : formatDate(order.date)}} {{order.end_time}}
                                </view>
                                <view class="room-price">总计 ¥ {{order.amount || 0}}</view>
                            </view>
                        </view>
                    </view>
                    <view class="order-footer">
                        <!-- 根据订单状态显示不同按钮 -->
                        <button v-if="order.status === 'canceled' || order.status === 'completed'" 
                                class="action-btn" @click.stop="deleteOrder(order.id)">删除订单</button>
                        <button v-if="order.status === 'pending'" 
                                class="action-btn pay-btn" @click.stop="goToPay(order.id)">去付款</button>
                        <button v-if="order.status === 'pending'" 
                                class="action-btn" @click.stop="cancelOrder(order.id)">取消订单</button>
                    </view>
                </view>
            </view>

            <!-- 无订单时显示 -->
            <view v-else class="empty-state">
                <image src="/static/icon/订单1.png" class="empty-icon"></image>
                <text class="empty-text">暂无订单记录</text>
            </view>
        </view>

        <!-- 加载更多 -->
        <view v-if="hasMore && orderList.length > 0" class="load-more" @click="loadMore">
            <text>{{loading ? '加载中...' : '加载更多'}}</text>
        </view>

        <!-- 底部导航栏 -->
        <tab-bar active="order"></tab-bar>
    </view>
</template>

<script lang="ts" setup>
import { ref, onMounted, onBeforeUnmount } from 'vue';
import TabBar from '@/components/tabBar/TabBar.vue';

// 设置导航栏标题
uni.setNavigationBarTitle({
    title: '我的订单'
});

// 当前激活的标签
const activeTab = ref('all');

// 订单数据列表
const orderList = ref([]);
const page = ref(1);
const pageSize = ref(10);
const hasMore = ref(true);
const loading = ref(false);

// 状态映射
const statusMap = {
    'pending': '待付款',
    'paid': '已支付',
    'confirmed': '未使用',
    'using': '使用中',
    'completed': '已完成',
    'canceled': '已取消'
};

// 获取状态对应的显示文本
const getStatusText = (status) => {
    return statusMap[status] || '未知状态';
};

// 获取状态对应的CSS类
const getStatusClass = (status) => {
    if (status === 'pending') return 'pending-status';
    return '';
};

// 格式化日期
const formatDate = (dateStr) => {
    if (!dateStr) return '';
    const date = new Date(dateStr);
    const month = (date.getMonth() + 1).toString().padStart(2, '0');
    const day = date.getDate().toString().padStart(2, '0');
    return `${month}-${day}`;
};

// 计算第二天日期
const formatNextDay = (dateStr) => {
    if (!dateStr) return '';
    const date = new Date(dateStr);
    date.setDate(date.getDate() + 1);
    const month = (date.getMonth() + 1).toString().padStart(2, '0');
    const day = date.getDate().toString().padStart(2, '0');
    return `${month}-${day}`;
};

// 加载订单数据
const loadOrders = async (reset = true) => {
    try {
        if (reset) {
            page.value = 1;
            hasMore.value = true;
        }
        
        if (loading.value || !hasMore.value) return;
        
        loading.value = true;
        
        // 构建查询参数
        let status = '';
        if (activeTab.value !== 'all') {
            status = activeTab.value;
        }
        
        // 调用API获取订单数据
        const token = uni.getStorageSync('token');
        if (!token) {
            uni.navigateTo({ url: '/pages/login/login' });
            return;
        }

        // 构建API URL
        const apiBaseUrl = process.env.VUE_APP_API_URL || '';
        
        const response = await uni.request({
            url: `${apiBaseUrl}/api/reservations/list`,
            method: 'GET',
            data: {
                page: page.value,
                pageSize: pageSize.value,
                status
            },
            header: {
                Authorization: `Bearer ${token}`
            }
        });
        
        const result = response[1].data;
        
        if (result.code === 200) {
            const orders = result.data || [];
            
            // 如果是第一页，重置列表
            if (page.value === 1) {
                orderList.value = orders;
            } else {
                // 否则追加数据
                orderList.value = [...orderList.value, ...orders];
            }
            
            // 判断是否还有更多数据
            hasMore.value = orders.length >= pageSize.value;
            page.value++;
        } else {
            uni.showToast({
                title: result.message || '获取订单失败',
                icon: 'none'
            });
        }
    } catch (error) {
        console.error('获取订单失败:', error);
        uni.showToast({
            title: '网络异常，请稍后重试',
            icon: 'none'
        });
    } finally {
        loading.value = false;
    }
};

// 加载更多数据
const loadMore = () => {
    if (!loading.value && hasMore.value) {
        loadOrders(false);
    }
};

// 切换标签
const switchTab = (tab) => {
    activeTab.value = tab;
    loadOrders(true);
};

// 跳转到订单详情页
const goToOrderDetail = (orderId) => {
    uni.navigateTo({
        url: `/pages/order/orderDetail?id=${orderId}`
    });
};

// 跳转到支付页面
const goToPay = (orderId) => {
    uni.navigateTo({
        url: `/pages/pay/pay?id=${orderId}&businessType=reservation`
    });
};

// 取消订单
const cancelOrder = async (orderId) => {
    try {
        uni.showModal({
            title: '确认取消',
            content: '确定要取消此订单吗？',
            success: async (res) => {
                if (res.confirm) {
                    const token = uni.getStorageSync('token');
                    const apiBaseUrl = process.env.VUE_APP_API_URL || '';
                    
                    const response = await uni.request({
                        url: `${apiBaseUrl}/api/reservations/cancel/${orderId}`,
                        method: 'POST',
                        header: {
                            Authorization: `Bearer ${token}`
                        }
                    });
                    
                    const result = response[1].data;
                    
                    if (result.code === 200) {
                        uni.showToast({
                            title: '订单已取消',
                            icon: 'success'
                        });
                        // 重新加载订单列表
                        loadOrders(true);
                    } else {
                        uni.showToast({
                            title: result.message || '取消订单失败',
                            icon: 'none'
                        });
                    }
                }
            }
        });
    } catch (error) {
        console.error('取消订单失败:', error);
        uni.showToast({
            title: '网络异常，请稍后重试',
            icon: 'none'
        });
    }
};

// 删除订单
const deleteOrder = (orderId) => {
    uni.showModal({
        title: '确认删除',
        content: '确定要删除此订单吗？删除后无法恢复',
        success: async (res) => {
            if (res.confirm) {
                try {
                    const token = uni.getStorageSync('token');
                    const apiBaseUrl = process.env.VUE_APP_API_URL || '';
                    
                    const response = await uni.request({
                        url: `${apiBaseUrl}/api/orders/delete/${orderId}`,
                        method: 'POST',
                        header: {
                            Authorization: `Bearer ${token}`
                        }
                    });
                    
                    const result = response[1].data;
                    
                    if (result.code === 200) {
                        uni.showToast({
                            title: '删除成功',
                            icon: 'success'
                        });
                        // 重新加载订单列表
                        loadOrders(true);
                    } else {
                        uni.showToast({
                            title: result.message || '删除订单失败',
                            icon: 'none'
                        });
                    }
                } catch (error) {
                    console.error('删除订单失败:', error);
                    uni.showToast({
                        title: '网络异常，请稍后重试',
                        icon: 'none'
                    });
                }
            }
        }
    });
};

// 处理全局tab切换事件
const handleGlobalTabChange = (tab) => {
    if (tab === 'order') return; // 当前已经是订单页，不需要处理

    const routes = {
        'home': '/pages/index/index',
        'coupon': '/pages/coupon/coupon',
        'user': '/pages/user/user'
    };

    const url = routes[tab];
    if (!url) return;

    // 尝试使用redirectTo，这对非tabBar页面有效
    uni.redirectTo({
        url,
        fail: () => {
            // 如果失败则尝试强制刷新到新页面
            if (typeof window !== 'undefined') {
                window.location.replace('#' + url);
            }
        }
    });
};

// 监听全局tab切换事件和加载订单数据
onMounted(() => {
    uni.$on('tabChange', handleGlobalTabChange);
    // 初始加载订单数据
    loadOrders();
});

// 组件销毁前移除事件监听
onBeforeUnmount(() => {
    uni.$off('tabChange', handleGlobalTabChange);
});
</script>

<style>
page {
    background-color: #f5f5f5;
    min-height: 100%;
}

.order-container {
    padding-bottom: 150rpx;
    padding-top: 0;
}

/* 标签滚动容器 */
.order-tab-scroll {
    width: 100%;
    background-color: #fff;
    white-space: nowrap;
    overflow: hidden;
}

/* 状态切换标签样式 */
.order-tab-bar {
    display: flex;
    justify-content: space-between;
    position: relative;
    border-bottom: 1px solid #f1f1f1;
}

.order-tab-item {
    display: inline-block;
    padding: 0 20rpx;
    height: 80rpx;
    line-height: 80rpx;
    font-size: 26rpx;
    color: #666;
    position: relative;
    text-align: center;
    flex: 1;
    min-width: 90rpx;
}

.order-tab-item.active {
    color: #333;
    font-weight: bold;
}

.tab-line {
    position: absolute;
    bottom: 0;
    left: 35%;
    width: 30%;
    height: 4rpx;
    background-color: #000;
}

/* 内容区域样式 */
.content {
    padding: 0;
    min-height: 70vh;
}

/* 订单列表样式 */
.order-list {
    width: 100%;
}

.order-item {
    background-color: #fff;
    margin: 20rpx;
    border-radius: 12rpx;
    box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
    overflow: hidden;
}

.order-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 24rpx 30rpx;
    border-bottom: 1rpx solid #f8f8f8;
}

.store-info {
    display: flex;
    align-items: center;
}

.store-icon {
    width: 44rpx;
    height: 44rpx;
    margin-right: 10rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    border-radius: 50%;
    overflow: hidden;
    background-color: #8BC398;
}

.icon-small {
    width: 40rpx;
    height: 40rpx;
    color: #fff;
}

.store-name {
    font-size: 28rpx;
    color: #333;
}

.order-status {
    font-size: 28rpx;
    color: #999;
}

.pending-status {
    color: #ff6600;
}

.order-content {
    padding: 24rpx 20rpx 24rpx 20rpx;
}

.room-info {
    display: flex;
    align-items: flex-start;
    flex-direction: row;
}

.room-image {
    width: 165rpx;
    height: 180rpx;
    border-radius: 8rpx;
    margin-right: 24rpx;
    object-fit: cover;
}

.room-details {
    flex: 1;
}

.room-name {
    font-size: 30rpx;
    color: #333;
    margin-bottom: 12rpx;
    font-weight: 500;
}

.room-time {
    font-size: 26rpx;
    color: #666;
    margin-bottom: 8rpx;
}

.room-reservation {
    font-size: 26rpx;
    color: #666;
    margin-bottom: 8rpx;
}

.time-no-wrap {
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
}

.room-price {
    font-size: 30rpx;
    color: #333;
    margin-top: 12rpx;
    font-weight: 500;
}

.order-footer {
    padding: 20rpx 30rpx 30rpx;
    display: flex;
    justify-content: flex-end;
    gap: 20rpx;
}

.action-btn {
    min-width: 160rpx;
    height: 60rpx;
    line-height: 60rpx;
    background-color: #fff;
    color: #666;
    font-size: 26rpx;
    padding: 0 20rpx;
    border: 1rpx solid #ddd;
    border-radius: 30rpx;
    margin: 0;
}

.pay-btn {
    background-color: #7FB992;
    color: #fff;
    border: none;
}

/* 没有订单的样式 */
.empty-state {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    padding: 100rpx 0;
    width: 100%;
}

.empty-icon {
    width: 120rpx;
    height: 120rpx;
    margin-bottom: 30rpx;
    opacity: 0.5;
}

.empty-text {
    font-size: 28rpx;
    color: #999;
}

/* 加载更多 */
.load-more {
    text-align: center;
    padding: 20rpx 0;
    color: #999;
    font-size: 26rpx;
}
</style> 